<?php
/**
 * Search Help : Missions
 * To select a mission and add all selected 
 * contact to it 
 */
/* @var $contact Hive\Ressource */
use Fox\Generator;
use Fox\Html\Input;
use Hive\Mission;
use Doctrine\DBAL\Connection;
use Fox\Dao\SqlFragment;

$xview = Xview::instance();
// Selected Contacts
$checkedContacts = $xview->val('checked',$xview->val('rids'));
if(!empty($checkedContacts)) {
	$checkedContacts = str_replace('"',"'",$checkedContacts);
} 
$jsonRids = addslashes($checkedContacts);
$searchHelp = new Fox\Html\SearchHelp("hive-missions");
$searchHelp->width("500");
$searchHelp->action = Generator::concatenate(Generator::ajax(
	Generator::url('missions','ressource','assign',
		array('missionid' => Generator::useAttribute('missionid'),
	)),"&data=$jsonRids",null,null,null,2
),";App.close('sh:hive-missions')","");

$searchHelp->block()
		->item("mission_description")
		->useLike()
		->size(20)
		->id("description");
$searchHelp
		->block()
		->item("mission_reference")
		->useLike()
		->size(20)->id("reference");
// Groups
$finder = new Hive\Ressource\Group();
$searchHelp
		->block()
		->item('mission_group')
		->options($finder->find(),'grouping','name');
$searchHelp
		->block()
		->item('mission_group')
		->id('grouping');		
if(!Fox\Authorization\Manager::check(Hive\Ressource::AUTH_GROUP_CAN_CHG)) {
	$searchHelp
		->block()->item('mission_group')->input(false);
}
		
$searchHelp->block()->add(new Input('rids',false,$checkedContacts))
			->excluded()
			->hidden(true);
$searchHelp->switchToObjectMode();
$searchHelp->grid()->fieldcat()->field("missionid")->SetHiddenInput(true)->hidden();
$searchHelp->grid()->fieldcat()->field("mission_reference")->width(100);

if(isset($_POST['dbcnt']))
{
	$inputs = $searchHelp->screen()->get();
	$fragments[] = $searchHelp->screen()->fragments();
	$finder = new Mission();
	$fragments[] = new SqlFragment('status NOT IN (?) OR status IS NULL',array(array(Mission::STATUS_CLOSED)),
			array(Connection::PARAM_STR_ARRAY));
	$res = $finder->find(Fox\Dao\SqlFragment::combine($fragments),array("title" => false),null,$_POST['dbcnt']);
	
	$searchHelp->grid()->fieldcat()->setGenerators(array(
		'mission_reference' => Fox\Generator::useAttribute('reference'),
		'mission_description' => Fox\Generator::useFunction(function($data) {
			return substr($data->description,0,40)."...";
		})
	));
	echo $searchHelp->displayGrid($res);
}
else
{
	echo $searchHelp->display();
}